//
//  cmei.c
//  knx_lib
//
//  Created by zym on 13-5-31.
//  Copyright (c) 2013年 Hinwo. All rights reserved.
//

#include "qt_knx.h"
#include <stdio.h>
#include <stdlib.h>
#include <QStringList>
#include "cmei.h"

void cmei_get_dest_addr(_u8 cemi_msg[],_u8 **addr)
{
    *addr = &cemi_msg[4];
}

void cmei_get_dest_addr_from_tunnelling(_u8 cemi_msg[],_u8 **addr)
{
    *addr = &cemi_msg[4];
}

void cmei_get_source_addr(_u8 cemi_msg[],_u8 **addr)
{
    *addr = &cemi_msg[2];
}

_int32 cmei_is_source_address_empty(_u8 cemi_msg[])
{
    if(cemi_msg[2] == 0 && cemi_msg[3]==0)
        return TRUE;
    return FALSE;
}

void cmei_get_device_data(_u8 cemi_msg[],_u8 **addr)
{
    *addr = &cemi_msg[6];
}

//cemi_data_msg means the data about cemi, not include the frame header.
_u8 cmei_get_control1(_u8 cemi_data_msg[])
{
    return cemi_data_msg[0];
}

_u8 cmei_get_control2(_u8 cemi_data_msg[])
{
    return cemi_data_msg[1];
}

_int32 is_group_address(_u8 control2)
{
    return (control2>>ADDR_TYPE_BIT)&GROUP_ADDR ;
}

void cmei_get_string_phy_address(char addr_msg[], _u8 PHY_IA[])
{
    _u8 arae = 0 , line = 0, index= 0;
    index = PHY_IA[1];
    line = PHY_IA[0] & 0xF;
    arae = (PHY_IA[0]>>4) & 0xF;

    sprintf((char *)addr_msg,"%u/%u/%u",arae,line,index);
}

void cmei_get_string_group_address(char addr_msg[],_u8 GA_IA[])
{
    _u8 arae = 0 , line = 0, index= 0;
    index = GA_IA[1];
    line = GA_IA[0] & 0x7;
    arae = (GA_IA[0]>>3) & 0x1F;

    sprintf((char *)addr_msg,"%u/%u/%u",arae,line,index);
}

bool cmei_set_group_address(_u8 addr_msg[], QByteArray gAddr)
{
    _u32 address[3] = {0},mask = 0x7,mainMask=0x1f;

    QStringList list = QString::fromLocal8Bit(gAddr).split("/");
    if(list.size() == 3)
    {
        address[0] = list.at(0).toUInt();
        address[1] = list.at(1).toUInt();
        address[2] = list.at(2).toUInt();
    }
    else
    {
        qDebug() << "cmei_set_group_address :  address not correct " << gAddr;
        return false;
    }

    addr_msg[0] = (_u8)(((address[0]&mainMask)<<3)|(address[1]&mask));     // dest address hi byte
    addr_msg[1] = (_u8)(address[2]&0xff);     // dest address lo byte

    return true;
}
